//  公共Js
var com = {
    /*********************************************** 检查权限 ***********************************************/
    checkAuth: function (dataType) {
        var userAuth = JSON.parse($.cookie("users")).userAuth;
        switch (dataType) {
            case "formCustoms":
                dataType = "users";
                break;
        }
        if (!userAuth.includes("*")) {
            if (!userAuth.includes(dataType + ".add")) {
                $("button[name='add']").remove();
            }
            if (!userAuth.includes(dataType + ".update")) {
                $("button[name='edit'],a[name='edit']").remove();
            } else {
                $("a[name='query']").remove();
            }
            if (!userAuth.includes(dataType + ".delete")) {
                $("button[name='delete'],a[name='delete']").remove();
            }
            if (!userAuth.includes(dataType + ".customs")) {
                $("button[name='customs']").remove();
            }
        } else {
            $("a[name='query']").remove();
        }
    },
    /*********************************************** 数据查询 ***********************************************/
    //  加载数据查询
    queryDatas: function (dataType) {
        switch (dataType) {
            case "menus":    //  菜单
            case "depts":    //  部门
            case "jobs":    //  职务
            case "dics":    //  字典
            case "sources":    //  客户来源
                document.querySelector('#table-tree').GM('setQuery', tree.loadParas(dataType));
                break;
            case "formCustoms":    //  用户自定义表单
                document.querySelector('#table-defined').GM('setQuery', tree.loadParas(dataType));
                break;
            default:
                document.querySelector('#table-data').GM('setQuery', table.loadParas(dataType));
                break;
        }
    },
    //  获取下拉选项数据
    querySelectDatas: function (obj, dataType) {
        $.ajax({
            url: '../com/querySelectDatas',
            type: 'get',
            dataType: 'json',
            async: false,
            data: {"dataType": dataType},
            success: function (data) {
                $.each(data, function (i, e) {
                    var strOption = "<option value='" + e.dkey + "'>" + e.dvalue + "</option>";
                    $("#" + obj).append(strOption);
                });
            }
        });
    },
    //  获取用户信息
    getUsers: function () {
        $.ajax({
            url: '../users/getUsers',
            type: 'POST',
            dataType: 'json',
            async: false,
            success: function (result) {
                com.loadFromItem(result.data);
            }
        });
    },
    //  获取自定义表单数据
    queryFormCustoms: function (dataType) {
        $.ajax({
            url: '../users/queryFormCustoms',
            type: 'get',
            dataType: 'json',
            async: false,
            data: {"modulename": dataType},
            success: function (data) {
                $("#h-defined").nextAll().remove();
                $.each(data, function (i, e) {
                    var strHtml = com.drawFormData(e);
                    $("#h-defined").after(strHtml);
                });
            }
        });
    },
    //  查询公告
    queryNotices: function () {
        $.ajax({
            url: '../com/queryNotices',
            type: 'get',
            dataType: 'json',
            async: false,
            success: function (data) {
                if (data.length == 0) {
                    $("#small-chat").hide();
                }
                $.each(data, function (i, e) {
                    $("#div-content").html(e.content_update);
                    $("#s-date").html(com.formateDateTime(e.createdate, 0));
                    $("#Hidnid").val(e.id);
                });
            }
        });
    },
    /*********************************************** 操作按钮 ***********************************************/
    //  加载图标按钮
    loadBtIcon: function (optType, e, dataType) {
        var iClass = "";
        var strAttr = "";
        var strColor = "";
        var title = "";
        switch (optType) {
            case "edit":    //  编辑
                title = "编辑";
                var jsonObj = JSON.stringify(e);
                iClass = "fa-edit";
                strAttr = "data-toggle='modal' data-target='#modal-form' onclick='com.clearFormItem(),com.loadFromItem(" + jsonObj + "),com.setTaskIsRead("+ jsonObj + ")'";
                strColor = ";color:forestgreen"
                break;
            case "query":   //  详情
                title = "详情";
                var jsonObj = JSON.stringify(e);
                iClass = "fa-search";
                strAttr = "data-toggle='modal' data-target='#modal-form' onclick='com.clearFormItem(),com.loadFromItem(" + jsonObj + ")'";
                strColor = ";color:forestgreen"
                break;
            case "delete":  //  删除
                title = "删除";
                iClass = "fa-trash";
                strAttr = "onclick=\"com.deleteMessage('" + e + "','" + dataType + "')\"";
                strColor = ";color:#dd5a43 !important";
                break;
            case "asc": //  降序
                title = "降序";
                iClass = "fa-level-down";
                strAttr = "";
                strColor = ";color:darkgray";
                if (e.orderbyid != e.maxsn) {
                    strAttr = "onclick=\"opt.setDataSn('" + e.menucode + "',1,'" + dataType + "')\"";
                    strColor = ";color:deepskyblue !important";
                }
                break;
            case "desc":    //  升序
                title = "升序";
                iClass = "fa-level-up";
                strAttr = "";
                strColor = ";color:darkgray";
                if (e.orderbyid != e.minsn) {
                    strAttr = "onclick=\"opt.setDataSn('" + e.menucode + "',0,'" + dataType + "')\"";
                    strColor = ";color:darkorchid !important";
                }
                break;
            case "submit":  //  提交
                title = "提交";
                iClass = "fa-send";
                strAttr = "onclick=\"opt.submitDatas('" + e + "','" + dataType + "')\"";
                strColor = ";color:#1c84c6 !important";
                break;
            case "export":  //  导出
                title = "导出";
                iClass = "fa-file-excel-o";
                strAttr = "onclick=\"opt.exportDatas('" + e + "','" + dataType + "')\"";
                strColor = ";color:blueviolet !important";
                break;
            case "takeback": //撤销
                title = "撤销";
                iClass = "fa-reply";
                strAttr = "onclick=\"opt.takebackDatas('" + e + "','" + dataType + "')\"";
                strColor = ";color:#dd5a43 !important";
                break;
        }

        return "<a data-tooltip=\"tooltip\" data-placement=\"top\" " + strAttr
            + " title='" + title + "' style='font-size: 15px; margin-left: 5px" +
            strColor + "' name='" + optType + "'><i class='fa " + iClass + "'></i></a>";
    },
    //  加载span标签
    loadSpan: function (title, styles) {
        return '<span class="label label-' + styles + '">' + title + '</span>';
    },
    /*********************************************** 表单处理 ***********************************************/
    //  清空表单
    clearFormItem: function (formName) {
        // console.log(formName)
        // var users = JSON.parse($.cookie("users"));
        // var currentdate = sendT.getCurrentT()
        formName = formName || 'myForm';
        $("#" + formName).valid();
        switch (formName) {
            case "pname":
                $(".treeSelect input:first").val("");
                break;
            default:
                // 获取表单元素
                var form = document.getElementById(formName);
                // 遍历表单元素
                for (var i = 0; i < form.elements.length; i++) {
                    var element = form.elements[i];
                    // 检查是否需要跳过重置
                    if (element.className.indexOf('no-reset') === -1) {
                        // 重置表单元素
                        if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
                            element.value = '';
                        } else if (element.nodeName === 'SELECT') {
                            element.selectedIndex = 0;
                        }
                    }
                }
                break;
        }
    },
    //  编辑时加载表单数据
    loadFromItem: function (e) {
        $.each(e, function (key, value) {   // e: 遍历的对象，function(): 回调函数，key: 元素索引， value: 当前的元素值
            switch (key) {
                case "pname":
                case "jobnames":
                case "deptnames":
                // case "maketaskuser": // 任务执行人
                    // $(".treeSelect input:first").val(value);
                    $("#txtPname").val(value);
                    break;
                case "taskfirstdate":  // 日期解析为yyyy-mm-dd
                case "taskplanenddate":
                case "taskenddate":
                case "taskfeedbackdate":
                case "latefeedbackdate":
                case "inquirydate":
                    $("#" + key).val(com.formateDateTime(value, 0));
                    break;
                case "menutype":
                    $("input[name='menutypes'][value='" + value + "']").click();
                    break;
                case "isSale":
                    $("input[name='sales'][value='" + value + "']").click();
                    if (value == 0) {
                        $("div[name='f-sales']").hide();
                    } else {
                        $("div[name='f-sales']").show();
                    }
                    break;
                case "isEffective":
                    $("#" + key).val(value);
                    // $("input[name='isEffectives']").attr("checked", value == 1 ? true : false);
                    if (value == 1) {
                        $("input[name='isEffectives']").click();
                    }
                    if ($("#HidModule").val() == 'menus') {
                        setSwitchery(mySwitch, value == 1 ? true : false);
                    }
                    break;
                case "jsondatas":
                    if (value) {
                        var jsonObj = JSON.parse(value);
                        if (jsonObj.length > 0) {
                            $.each(jsonObj, function (i, f) {
                                $("#" + f.key).val(f.value);
                            });
                        }
                    }
                    break;
                case "cussource":   //  客户来源
                    $("#"+key).val(value);
                    $("#txtPname").val(value);
                    break;
                case "tclass":
                    $("#"+key).val(value);
                    changeTclass("#"+key);
                    break;
                case "sendtaskuser":
                    $("#sendtaskuser").val(e.sendtaskuser);
                    break;
                case "taskfirstdate":
                    $("#taskfirstdate").val(table.formatterDate(e.taskfirstdate));
                    break;
                default:
                    //  普通文本赋值
                    $("#" + key).val(value);
                    break;
            }
        });
    },
    //  获取数据操作 optionType:0保存，1删除，2加载
    loadUrl: function (dataType, optionType) {
        var url = "";
        var methodName = "";
        switch (dataType) {
            case "menus":    //  菜单
                methodName = optionType == 0 ? "saveMenus" : "queryMenus";
                url = '../menus/' + methodName;
                break;
            case "depts":    //  部门
                methodName = optionType == 0 ? "saveDepts" : "queryDepts";
                url = '../depts/' + methodName;
                break;
            case "dics":    //  字典
                methodName = optionType == 0 ? "saveDics" : "queryDics";
                url = '../sys/' + methodName;
                break;
            case "notices":    //  公告
                methodName = optionType == 0 ? "saveNotices" : "queryNotices";
                url = '../sys/' + methodName;
                break;
            case "msgs":    //  消息
                methodName = "queryMsgs";
                url = '../sys/' + methodName;
                break;
            case "jobs":    //  职务
                methodName = optionType == 0 ? "saveJobs" : "queryJobs";
                url = '../comp/' + methodName;
                break;
            case "users":    //  用户
                methodName = optionType == 0 ? "saveUsers" : "queryUsers";
                url = '../users/' + methodName;
                break;
            case "formCustoms":    //  自定义表单
                methodName = optionType == 0 ? "saveFormCustoms" : "queryFormCustoms";
                url = '../users/' + methodName;
                break;
            case "cus":    //  客户档案
                methodName = optionType == 0 ? "saveCustomes" : "queryCustomes";
                url = '../cus/' + methodName;
                break;
            case "sources":    //  客户来源
                methodName = optionType == 0 ? "saveCusSources" : "queryCusSources";
                url = '../cus/' + methodName;
                break;
            case "orders":    //  工单管理
                methodName = optionType == 0 ? "" : "queryOrders";
                url = '../works/' + methodName;
                break;
            case "orderType":    //  工单类型
                methodName = optionType == 0 ? "saveOrderTypes" : "queryOrderTypes";
                url = '../works/' + methodName;
                break;
            case "tasklst":     //  任务派发
                methodName = optionType == 0 ? "saveTasklst" : "queryTasklst";
                url= '../tasklst/' + methodName;
                break;
            case "inquiry":     //   货代询价
                methodName = optionType == 0 ? "saveInquiry" : "queryInquiry";
                url= '../inquiry/' + methodName;
        }
        return url;
    },
    //  渲染自定义表单
    drawFormData: function (e) {
        var strHtml = "";
        var required = e.isrequired ? "required" : "";
        var lSpot = e.isrequired ? 'l="spot"' : "";
        strHtml += '<div class="form-group">';
        strHtml += '    <label class="col-sm-3 control-label" ' + lSpot + '>' + e.fname + '：</label>';
        strHtml += '    <div class="col-sm-8">';
        /** 表单类型：0文本;1下拉选项，2日期，3大文本 */
        switch (e.ftype) {
            case 1: //  下拉选项
                strHtml += '<select id="d-' + e.fcode + '" name="d-' + e.fcode + '" class="form-control">';
                $.each(JSON.parse(e.optionjson), function (j, d) {
                    strHtml += '<option value="' + d.value + '">' + d.value + '</option>'
                });
                strHtml += '</select>';
                break;
            case 3: //  3大文本
                strHtml += '   <textarea type="text" class="form-control" rows="3" id="d-' + e.fcode + '"' +
                    '          name="d-' + e.fcode + '" placeholder="请输入' + fname + '"></textarea>';
                break;
            default:
                strHtml += '<input id="d-' + e.fcode + '" name="d-' + e.fcode + '" class="form-control" ' + required + ' type="text">';
                break
        }
        strHtml += '    </div>';
        strHtml += '</div>';
        return strHtml;
    },
    //  自定义数据赋值
    setDefinedVal: function (name, obj, fName) {
        var dataDefined = [];
        $(fName + " input[name^='" + name + "']").each(function (i, e) {
            var strOptionItems = {};
            strOptionItems["key"] = $(this).attr("name");
            strOptionItems["value"] = $(this).val();
            dataDefined.push(strOptionItems);
        });
        $(fName + " select[name^='" + name + "']").each(function (i, e) {
            var strOptionItems = {};
            var sname = $(this).attr("name");
            strOptionItems["key"] = sname;
            strOptionItems["value"] = $(this).val();
            dataDefined.push(strOptionItems);
        });
        $("#" + obj).val(JSON.stringify(dataDefined));
    },
    //  加载自定义表单值
    clearFormData: function () {
        document.getElementById('myForm-defined').reset();
        $("#div-option-0").hide();
        $("#div-option-0").nextAll().remove();
    },
    //  设置根级名称
    setRootName: function () {
        $("#txtPname").val("根级");
    },
    //设置为已读
    setTaskIsRead: function (e){
        let user = JSON.parse($.cookie("users"));
        if(user.name === e.maketaskuser){
            $.ajax({
                url: '../tasklst/taskIsRead',
                type: 'post',
                dataType: 'json',
                data: {dataId: e.id,},
                async: false,
                success: function (result) {
                    if(result.resultCode == 200){
                        console.log('当前记录已读')
                    }
                }
            })
        }
    },
    //  清除查询表单项
    clearSearch : function (){
        $("input[name^='query']").val("");
        $("input[name^='search']").val("");
        $("select[name^='query']").val("");
    },
    /*********************************************** 信息提示 ***********************************************/
    //  信息提示
    alterMessage: function (title, type) {
        swal({
            title: title,
            // text: text,
            type: type,
            buttonsStyling: false,
            timer: 1500,
            showConfirmButton: false,
            // confirmButtonClass: 'btn btn-sm btn-light',
            background: 'rgba(0, 0, 0, 0.96)'
        });
    },
    //  删除提示
    deleteMessage: function (dataId, dataType) {
        var title = "确认要删除此信息?";
        switch (dataType) {
            case "menus":
                title = "删除菜单后，该菜单所有子集也将被删除，请谨慎操作！";
                break;
            case "dept":
                title = "删除部门后该部门所有数据都将被删除，请谨慎操作！";
                break;
        }
        swal({
            title: title,
            text: "删除后将无法恢复，请谨慎操作！",
            type: 'warning',
            showCancelButton: true,
            buttonsStyling: false,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: '确认删除',
            cancelButtonClass: 'btn btn-light',
            cancelButtonText: '取消',
            closeOnConfirm: false
        }, function () {
            opt.deleteDatas(dataId, dataType);
        });
    },
    //  批量删除提示
    deleteAllMessage: function (dataType, tName) {
        var strIds = "";
        // console.log( $("input[name='checkItems']"))
        switch (dataType) {
            case "menus":
            case "depts":
            case "jobs":
            case "dics":
            case "cus":
            case "sources":
                $("input[name='checkItems']").each(function () {
                    if (this.checked) {
                        strIds += $(this).val() + ",";
                    }
                });
                break;
            console.log(strIds)
            default:
                strIds = $("#HiddataIds").val();
                break;
        }
        if (strIds.length == 0) {
            com.alterMessage("请选择要删除的数据！", "warning");
            return;
        }
        var title = "确认要删除选中的信息?";
        switch (dataType) {
            case "menus":
                title = "删除菜单后，该菜单所有子集也将被删除，请谨慎操作！";
                break;
            case "dept":
                title = "删除部门后该部门所有数据都将被删除，请谨慎操作！";
                break;
        }
        swal({
            title: title,
            type: 'warning',
            showCancelButton: true,
            buttonsStyling: false,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: '确认删除',
            cancelButtonClass: 'btn btn-light',
            cancelButtonText: '取消',
            closeOnConfirm: false
        }, function () {
            opt.deleteAllDatas(strIds, dataType, tName);
        });
    },
    // 完成提示
    FromComplateMsg: function (dataType) {
        var strIds = "";
        // strIds += $(this).val() + ",";
        console.log(dataType)
        switch (dataType) {
            case "inquiry":
                $("input[name='checkItems']").each(function () {
                    if (this.checked) {
                        strIds += $(this).val() + ",";
                    }
                });
                break;
            default:
                strIds = $("#HiddataIds").val();
                break;
        }
        console.log(strIds)
        if (strIds.length == 0) {
            com.alterMessage("哪条完事了？选一下呢~", "warning");
            return;
        }
        var title = "确认要执行此完成操作？";
        switch (dataType) {
            case "inquiry":
                title = title;
                break;
        }
        swal({
            title: title,
            text: "",
            type: 'info',
            showCancelButton: true,
            buttonsStyling: false,
            confirmButtonColor: "#4ec9ea",
            confirmButtonText: '确认',
            cancelButtonClass: 'btn btn-light',
            cancelButtonText: '取消',
            closeOnConfirm: false
        }, function () {
            opt.FromComplate(strIds, dataType);
        });
    },
    /*********************************************** 数据操作 ***********************************************/
    //  批量选择
    checkAlls: function () {
        if ($("input[name='checkAll']").is(":checked")) {
            $("input[name='checkItems']").prop("checked", true);
            $("#bt-del, #bt-complate").attr("disabled", false);
        } else {
            $("input[name='checkItems']").prop("checked", false);
            $("#bt-del,#bt-complate").attr("disabled", true);
        }
    },
    checkItems: function () {
        var strIds = "";
        $("input[name='checkItems']").each(function () {
            if (this.checked) {
                strIds += $(this).val() + ",";
            }
        });
        $("#bt-del, #bt-complate").attr("disabled", strIds.length > 0 ? false : true);
    },
    //  自定义表单-添加自定义选项
    addOptions: function () {
        var index = $("div[name='div-option']").length;
        var strHtml = "";
        strHtml += '<div class="form-group" name="div-option" id="div-option-' + index + '">';
        strHtml += '    <label class="col-sm-3 control-label"></label>';
        strHtml += '    <div class="col-sm-4">';
        strHtml += '        <input type="text" id="optionname-' + index + '" name="optionname-' + index + '"';
        strHtml += '               class="form-control" placeholder="请输入选项名称">';
        strHtml += '    </div>';
        strHtml += '    <div class="col-sm-4">';
        strHtml += '        <button type="button" class="btn btn-info btn-sm"';
        strHtml += '                onClick="com.addOptions()">新增';
        strHtml += '        </button>';
        strHtml += '        <button type="button" class="btn btn-danger btn-sm"';
        strHtml += '                onClick="com.delOptions(' + index + ')">删除';
        strHtml += '        </button>';
        strHtml += '    </div>';
        strHtml += '</div>';
        $("#div-option-0").after(strHtml);
    },
    //  删除选项
    delOptions: function (index) {
        $("#div-option-" + index).remove();
    },
    /*********************************************** 日期 ***********************************************/
    //  日期转换
    formateDateTime: function (d, type) {
        if (d != undefined) {
            var date = new Date(d);
            var yyyy = date.getFullYear(), mm = (date.getMonth() + 1).toString(), dd = date.getDate().toString();
            var hh = date.getHours();
            var m0 = date.getMinutes();
            var ss = date.getSeconds();
            if (mm < 10) {
                mm = '0' + mm;
            }
            if (dd < 10) {
                dd = '0' + dd;
            }
            if (hh < 10) {
                hh = '0' + hh;
            }
            if (m0 < 10) {
                m0 = '0' + m0;
            }
            if (ss < 10) {
                ss = '0' + ss;
            }
            switch (type) {
                case 0:
                    return (yyyy + '-' + mm + '-' + dd);
                    break;
                case 1:
                    return (yyyy + '-' + mm + '-' + dd + " " + hh + ":" + m0);
                    break;
                case 2:
                    return (yyyy + '-' + mm + '-' + dd + " " + hh + ":" + m0 + ":" + ss);
                    break;
                default:
                    return (yyyy + '-' + mm + '-' + dd + " " + hh + ":" + m0 + ":" + ss);
                    break;
            }
        } else {
            return "--";
        }
    },
    /*********************************************** 系统操作 ***********************************************/
    //  退出登录
    outLogin: function () {
        $.ajax({
            url: '../users/outLogin',
            type: 'POST',
            dataType: 'json',
            async: false,
            success: function (data) {
                window.location.href = 'Login.jsp';
            }
        });
    }
}